﻿// Copyright (C) Norsolutions GmbH
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Reng van Oord
// Created:    2010.05.05

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Sherwood.Mvc.Html
{
    /// <summary>
    /// Provides an enumeration list source for an ASP.Net MVC drop down list.
    /// Value corresponds to the enumeration integer value. 
    /// Text is the enumeration item name. "_" is automatically replaced with a space and "Unspecified" is automatically replaced with "" (blank).
    /// </summary>
    public class EnumSelectList
    {
        public static List<SelectListItem> GetList(Type enumType, object selectedValue, bool translate)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            if (enumType.IsEnum)
            {
                string[] names = Enum.GetNames(enumType);
                Array values = Enum.GetValues(enumType);
                for (int i = 0; i < names.Length; i++)
                {
                    SelectListItem item = new SelectListItem();
                    if (names[i].Equals("Unspecified", StringComparison.OrdinalIgnoreCase))
                    {
                        item.Text = "";
                    }
                    else
                    {
                        if (translate)
                            item.Text = "[!" + names[i].Replace("_", " ") + "!]";
                        else
                            item.Text = names[i].Replace("_", " ");

                    }
                    item.Value = ((int)values.GetValue(i)).ToString();
                    int selectedEnumValue = 0;
                    if (selectedValue != null)
                    {
                        try
                        {
                            int selectedValueInt = 0;
                            if (int.TryParse(selectedValue.ToString(), out selectedValueInt))
                            {
                                selectedEnumValue = selectedValueInt;
                            }
                            else
                            {
                                selectedEnumValue = Convert.ToInt32(Enum.Parse(enumType, selectedValue.ToString()));
                            }
                        }
                        catch
                        {
                        }
                    }
                    item.Selected = selectedValue != null && Convert.ToInt32(values.GetValue(i)).Equals(selectedEnumValue);
                    items.Add(item);
                }
            }

            return items;
        }
    }
}
